package com.lanhai.longheng.listener;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lanhai.longheng.beans.AgvDataBean;
import com.lanhai.longheng.dispatch.DispatchAgv;
import com.lanhai.longheng.interfaces.IAgv; 
 

/**
 *  小车的消息获取
 * @author virus408
 *
 */
@Component
public class AgvListener {
	@Autowired 
	DispatchAgv dAgv;
	
	@Autowired
	IAgv iagv;
	
	
	private boolean running;
	private Thread th;
	
	public void Start(int port) {
		running=true;
		System.out.println("启动AGV侦听线程");
		th=new Thread() { 
			@Override
			public void run() {
				try{ 
					DatagramSocket	ds = new DatagramSocket(port);
					while(running){
						byte buf[] = new byte[20];
						DatagramPacket dp = new DatagramPacket(buf, buf.length);
						ds.receive(dp);
					 
						
						if(buf[0]==-95) {
							//只处理小车的
							AgvDataBean bb=iagv.analyseData(buf);
							if(bb!=null) {
								dAgv.resolve(bb); 
							}
							
						} 
					}	
					ds.close();
				}catch(Exception e){
					e.printStackTrace();
				}	
			}
			
		};
		th.start();
	}
	 
	
	public void Stop() {
		running=false;
		try {
			th.interrupt();
			th=null; 
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
